import React, { useState, useEffect, useCallback } from 'react';
import {
  Card, Row, Col, Statistic, Progress, Table, Tag, Button, Space, Modal, Form, 
  Input, Switch, message, Typography, Tooltip, Badge, Alert, Timeline, Tabs, Select, Spin
} from 'antd';
import BaseTable from '../shared/table/BaseTable';
import {
  CloudServerOutlined, DatabaseOutlined, CloudOutlined, SafetyOutlined, SettingOutlined, 
  ReloadOutlined, ExclamationCircleOutlined, CheckCircleOutlined, CloseCircleOutlined, 
  SyncOutlined, EditOutlined, SaveOutlined, EyeOutlined, HistoryOutlined, BellOutlined, 
  UserOutlined, LockOutlined, GlobalOutlined, MailOutlined, PhoneOutlined, WechatOutlined, DownloadOutlined
} from '@ant-design/icons';
import api from '../utils/api';
import dayjs from 'dayjs';
import { getErrorMessage, getSuccessMessage, getHttpErrorMessage, PAGES, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { TextArea } = Input;

const System = () => {
  const [loading, setLoading] = useState({ info: false, config: false, logs: false, backups: false });
  const [error, setError] = useState({ info: null, config: null, logs: null, backups: null });
  const [systemInfo, setSystemInfo] = useState(null);
  const [systemConfig, setSystemConfig] = useState(null);
  const [systemLogs, setSystemLogs] = useState([]);
  const [backupHistory, setBackupHistory] = useState([]);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [editingConfig, setEditingConfig] = useState(null);
  const [form] = Form.useForm();

  const fetchData = useCallback(async (dataType) => {
    setLoading(prev => ({ ...prev, [dataType]: true }));
    setError(prev => ({ ...prev, [dataType]: null }));
    try {
      const response = await api.get(`/admin/system/${dataType}`);
      if (dataType === 'info') setSystemInfo(response.data);
      if (dataType === 'config') setSystemConfig(response.data);
      if (dataType === 'logs') setSystemLogs(response.data);
      if (dataType === 'backups') setBackupHistory(response.data);
    } catch (err) {
      setError(prev => ({ ...prev, [dataType]: `获取${dataType}数据失败` }));
      message.error(`获取${dataType}数据失败`);
    } finally {
      setLoading(prev => ({ ...prev, [dataType]: false }));
    }
  }, []);

  useEffect(() => {
    fetchData('info');
    fetchData('config');
    fetchData('logs');
    fetchData('backups');
  }, [fetchData]);

  const getStatusColor = (status) => {
    const colors = { running: 'success', connected: 'success', normal: 'success', stable: 'success', stopped: 'error', disconnected: 'error', error: 'error', warning: 'warning' };
    return colors[status] || 'default';
  };

  const getStatusIcon = (status) => {
    const icons = { running: <CheckCircleOutlined />, connected: <CheckCircleOutlined />, normal: <CheckCircleOutlined />, stable: <CheckCircleOutlined />, stopped: <CloseCircleOutlined />, disconnected: <CloseCircleOutlined />, error: <ExclamationCircleOutlined />, warning: <ExclamationCircleOutlined /> };
    return icons[status] || <CheckCircleOutlined />;
  };

  const getLogTypeColor = (type) => ({ info: 'blue', success: 'green', warning: 'orange', error: 'red' }[type] || 'default');
  const getLogTypeIcon = (type) => ({ info: <ExclamationCircleOutlined />, success: <CheckCircleOutlined />, warning: <ExclamationCircleOutlined />, error: <CloseCircleOutlined /> }[type] || <ExclamationCircleOutlined />);
  const getProgressStatus = (value) => {
    if (value >= 80) return 'exception';
    if (value >= 60) return 'active';
    return 'normal';
  };

  const handleConfigEdit = (configType) => {
    setEditingConfig(configType);
    form.setFieldsValue(systemConfig[configType]);
    setConfigModalVisible(true);
  };

  const handleConfigSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(prev => ({ ...prev, config: true }));
      await api.put('/admin/system/config', { [editingConfig]: values });
      setSystemConfig(prev => ({ ...prev, [editingConfig]: values }));
      message.success(getSuccessMessage(PAGES.SYSTEM, SUCCESS_TYPES.SAVE_SUCCESS));
      setConfigModalVisible(false);
      setEditingConfig(null);
      form.resetFields();
    } catch (error) {
      message.error(getErrorMessage(PAGES.SYSTEM, ERROR_TYPES.SAVE_FAILED));
    } finally {
      setLoading(prev => ({ ...prev, config: false }));
    }
  };

  const handleBackup = () => {
    Modal.confirm({ title: '手动备份', content: '确定要立即执行数据库备份吗？', okText: '确定', cancelText: '取消', onOk: async () => {
      message.loading('正在备份数据库...', 2);
      try {
        const response = await api.post('/admin/system/backups');
        setBackupHistory([response.data, ...backupHistory]);
        message.success(getSuccessMessage(PAGES.SYSTEM, 'BACKUP_SUCCESS'));
      } catch (error) { message.error(getErrorMessage(PAGES.SYSTEM, 'BACKUP_FAILED')); }
    }});
  };

  const handleRestart = () => {
    Modal.confirm({ title: '重启系统', content: '确定要重启系统吗？这将暂时中断服务。', okText: '确定', cancelText: '取消', onOk: async () => {
      message.loading('正在重启系统...', 3);
      try {
        await api.post('/admin/system/restart');
        setTimeout(() => { message.success(getSuccessMessage('SYSTEM', SUCCESS_TYPES.SYSTEM_RESTART_SUCCESS)); window.location.reload(); }, 3000);
      } catch (error) { message.error(getErrorMessage('SYSTEM', ERROR_TYPES.SYSTEM_RESTART_FAILED)); }
    }});
  };

  const handleDownloadBackup = async (record) => {
    try {
      const response = await api.get(`/admin/system/backups/${record.id}/download`, {
        responseType: 'blob'
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', record.filename);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      message.success(getSuccessMessage('SYSTEM', SUCCESS_TYPES.SYSTEM_DOWNLOAD_SUCCESS));
    } catch (error) {
      message.error(getErrorMessage('SYSTEM', ERROR_TYPES.SYSTEM_DOWNLOAD_FAILED));
    }
  };

  const handleDeleteBackup = (backupId) => {
    Modal.confirm({
      title: '删除备份',
      content: '确定要删除这个备份文件吗？删除后无法恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await api.delete(`/admin/system/backups/${backupId}`);
          setBackupHistory(backupHistory.filter(backup => backup.id !== backupId));
          message.success(getSuccessMessage('SYSTEM', SUCCESS_TYPES.SYSTEM_DELETE_SUCCESS));
        } catch (error) {
          message.error(getErrorMessage('SYSTEM', ERROR_TYPES.SYSTEM_DELETE_FAILED));
        }
      }
    });
  };

  const systemStatusCards = [
    { title: '服务器状态', value: systemInfo?.serverStatus, icon: <CloudServerOutlined />, color: '#1890ff' },
    { title: '数据库状态', value: systemInfo?.databaseStatus, icon: <DatabaseOutlined />, color: '#52c41a' },
    { title: '缓存状态', value: systemInfo?.cacheStatus, icon: <CloudOutlined />, color: '#722ed1' },
    { title: '存储状态', value: systemInfo?.storageStatus, icon: <SafetyOutlined />, color: '#faad14' }
  ];

  const logColumns = [
    { title: '类型', dataIndex: 'type', key: 'type', width: 80, render: (type) => <Tag color={getLogTypeColor(type)} icon={getLogTypeIcon(type)}>{type.toUpperCase()}</Tag> },
    { title: '消息', dataIndex: 'message', key: 'message' },
    { title: '模块', dataIndex: 'module', key: 'module', width: 100, render: (module) => <Tag>{module}</Tag> },
    { title: '用户', dataIndex: 'user', key: 'user', width: 100 },
    { title: '时间', dataIndex: 'timestamp', key: 'timestamp', width: 160, render: (ts) => dayjs(ts).format('YYYY-MM-DD HH:mm:ss') }
  ];

  const backupColumns = [
    { title: '文件名', dataIndex: 'filename', key: 'filename' },
    { title: '大小', dataIndex: 'size', key: 'size', width: 100 },
    { title: '类型', dataIndex: 'type', key: 'type', width: 80, render: (type) => <Tag color={type === 'auto' ? 'blue' : 'green'}>{type === 'auto' ? '自动' : '手动'}</Tag> },
    { title: '状态', dataIndex: 'status', key: 'status', width: 80, render: (status) => <Tag color={status === 'success' ? 'success' : 'error'}>{status === 'success' ? '成功' : '失败'}</Tag> },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 160, render: (ts) => dayjs(ts).format('YYYY-MM-DD HH:mm:ss') },
    { title: '操作', key: 'action', width: 120, render: (_, record) => (
      <Space>
        <Tooltip title="下载"><Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadBackup(record)} /></Tooltip>
        <Tooltip title="删除"><Button size="small" danger icon={<CloseCircleOutlined />} onClick={() => handleDeleteBackup(record.id)} /></Tooltip>
      </Space>
    )}
  ];

  const renderConfigForm = () => {
    if (!editingConfig || !systemConfig) return null;
    const configGroup = systemConfig[editingConfig];
    return (
      <Form form={form} layout="vertical" initialValues={configGroup}>
        {Object.keys(configGroup).map(key => {
          const field = configGroup[key];
          if (typeof field === 'boolean') {
            return <Form.Item key={key} name={key} valuePropName="checked" label={key}><Switch /></Form.Item>;
          }
          return <Form.Item key={key} name={key} label={key}><Input /></Form.Item>;
        })}
      </Form>
    );
  };

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}><SettingOutlined /> 系统管理</Title>
      <Tabs defaultActiveKey="status" type="card">
        <TabPane tab={<span><CloudServerOutlined />系统状态</span>} key="status">
          {loading.info && <Spin />}
          {error.info && <Alert message={error.info} type="error" />}
          {systemInfo && <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            {systemStatusCards.map((card, index) => (
              <Col xs={24} sm={12} lg={6} key={index}>
                <Card><Statistic title={card.title} value={card.value} prefix={card.icon} valueStyle={{color: getStatusColor(card.value)}} /></Card>
              </Col>
            ))}
          </Row>}
          {systemInfo && <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} lg={8}><Card title="CPU使用率"><Progress type="circle" percent={Math.round(systemInfo.cpuUsage)} status={getProgressStatus(systemInfo.cpuUsage)} /></Card></Col>
            <Col xs={24} lg={8}><Card title="内存使用率"><Progress type="circle" percent={Math.round(systemInfo.memoryUsage)} status={getProgressStatus(systemInfo.memoryUsage)} /></Card></Col>
            <Col xs={24} lg={8}><Card title="磁盘使用率"><Progress type="circle" percent={systemInfo.diskUsage} status={getProgressStatus(systemInfo.diskUsage)} /></Card></Col>
          </Row>}
        </TabPane>
        <TabPane tab={<span><SettingOutlined />系统配置</span>} key="config">
          {loading.config && <Spin />}
          {error.config && <Alert message={error.config} type="error" />}
          {systemConfig && <Card>
            {Object.keys(systemConfig).map(group => (
              <Card key={group} title={group} extra={<Button icon={<EditOutlined />} onClick={() => handleConfigEdit(group)}>编辑</Button>}>
                <ul>{Object.keys(systemConfig[group]).map(key => <li key={key}><strong>{key}:</strong> {String(systemConfig[group][key])}</li>)}</ul>
              </Card>
            ))}
          </Card>}
        </TabPane>
        <TabPane tab={<span><HistoryOutlined />系统日志</span>} key="logs">
          <Button onClick={() => fetchData('logs')} loading={loading.logs} icon={<ReloadOutlined />}>刷新</Button>
          <BaseTable dataSource={systemLogs} columns={logColumns} loading={loading.logs} rowKey="id" />
        </TabPane>
        <TabPane tab={<span><DatabaseOutlined />数据备份</span>} key="backups">
          <Space style={{ marginBottom: 16 }}>
            <Button type="primary" onClick={handleBackup}>手动备份</Button>
            <Button onClick={() => fetchData('backups')} loading={loading.backups} icon={<ReloadOutlined />}>刷新</Button>
          </Space>
          <BaseTable dataSource={backupHistory} columns={backupColumns} loading={loading.backups} rowKey="id" />
        </TabPane>
      </Tabs>
      <Modal title={`编辑 ${editingConfig} 配置`} visible={configModalVisible} onOk={handleConfigSave} onCancel={() => setConfigModalVisible(false)} confirmLoading={loading.config}>
        {renderConfigForm()}
      </Modal>
    </div>
  );
};

export default System;